import {RecordCategory, RecordType} from "../record.js";
import {ErrorDefinition} from "./error-def.js";

export class EventDiagnose {
    constructor() {
        this.clear();
    }

    clear() {
        this.eventIdsToRecords = new Map();
        this.errors = [];
        this.errorsCacheValid = false;
    }

    addRecord(rec) {
        if (rec.category !== RecordCategory.Event) {
            return;
        }
        this.errorsCacheValid = false;
        let records = this.eventIdsToRecords.get(rec.eventId);
        if (records === undefined) {
            this.eventIdsToRecords.set(rec.eventId, [rec]);
        } else {
            records.push(rec);
        }
    }

    reGetErrors() {
        this.errors = [];
        for (let eventIdAndRecords of this.eventIdsToRecords) {
            let records = eventIdAndRecords[1];
            for (let i = 0; i < records.length;) {
                if (i + 1 >= records.length) {
                    this.errors.push({
                        type: ErrorDefinition.eventNotPair,
                        records: [records[i]]
                    });
                    ++i;
                    continue;
                }
                if (records[i].type === RecordType.waitEvent && records[i + 1].type === RecordType.sendEvent) {
                    this.errors.push({
                        type: ErrorDefinition.incorrectEventOrder,
                        records: [records[i], records[i + 1]]
                    });
                    i += 2;
                    continue;
                }
                if ((records[i].type === RecordType.waitEvent && records[i + 1].type === RecordType.waitEvent)
                    || (records[i].type === RecordType.sendEvent && records[i + 1].type === RecordType.sendEvent)) {
                    this.errors.push({
                        type: ErrorDefinition.eventNotPair,
                        records: records.slice(i, records.length)
                    });
                    i = records.length;
                    continue;
                }
                // other diagnose ...
                i += 2;
            }
        }
    }

    getErrors() {
        if (!this.errorsCacheValid) {
            this.reGetErrors();
        }
        this.errorsCacheValid = true;
        return this.errors;
    }
}